package it.unibo.deis.lia.mmhc.spm;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Vector;

public class SocketVector {

	private Vector<LocalServiceSocket> allSocket = new Vector<LocalServiceSocket>();

	private static SocketVector socketVector = null;

	public synchronized static SocketVector getInstance() {
		if (socketVector == null) {
			socketVector = new SocketVector();
			return socketVector;
		} else
			return socketVector;
	}

	protected void addSocket(String name, int port, Socket input){
		allSocket.add(new LocalServiceSocket(name,port,input));
	}
	
	protected Socket getSoket(String name, int port) {
		LocalServiceSocket socket = null;
		for (int i = 0; i < allSocket.size(); i++) {
			socket = allSocket.elementAt(i);
			if (socket.getName().equalsIgnoreCase(name)
					&& socket.getPorta() == port)
				if (socket.getSock().isClosed()){
					allSocket.removeElementAt(i);
					break;}
				else
					return socket.getSock();}
				

					try {
						int attempts = 5;
						// String hop = packet.nextHop();
						Socket newsocket = null;
						do {
							try {
								newsocket = new Socket(name, port);
							} catch (Exception e) {
								try {
									Thread.sleep(1500);
									attempts--;
									if (attempts == 0)
										throw e;
									System.err
											.println("Impossibile aprire o trovare socket di risposta "
													+ e);
								} catch (Exception e1) {
									// TODO: handle exception
								}
							}
						} while (attempts > 0 && newsocket == null);
						allSocket.add(new LocalServiceSocket(name, port,
								newsocket));
						return newsocket;
					} catch (Exception e) {
						System.err
								.println("Problemi nella gestione del vettore delle socket impossibile creare una nuova socket");
						e.printStackTrace();

						
					}
					
				
			
		
		return null;
	}
}
